package dataAccess;

import businessEntities.MainLogger;
import businessEntities.exceptions.ConnectionException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

class SingeltonConnection {

    static Connection _singeltonConnection;
    static String _host;
    static String _userName;
    static String _password;
    static String _port;

    /**
     * @throws ConnectionException if the connection to the database is not reachable.
     **/
    static Connection getConnection() {
        try {
            if ((_singeltonConnection == null) || _singeltonConnection.isClosed()) {
                initConnection();
            }
        } catch (SQLException | ConnectionException ex) {
            MainLogger.logger.error("The connection to the server at [" + _host + ":" + _port + "] is not reachable.", ex);
            throw new ConnectionException("The connection to the server at [" + _host + ":" + _port + "] is not reachable.", ex);
        }

        return _singeltonConnection;

    }

    private static Connection initConnection() {
        try {
            MainLogger.logger.info("Initialize connection to : [" + _host + ":" + _port + "]");
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            String path = "jdbc:mysql://" + _host + ":" + _port;
            _singeltonConnection = DriverManager.getConnection(path, _userName, _password);
        } catch (ClassNotFoundException | IllegalAccessException | SQLException | InstantiationException ex) {
            if (_singeltonConnection != null) {
                try {
                    _singeltonConnection.close();
                } catch (SQLException closeEx) {/*Empty*/

                }
            }
            throw new ConnectionException("Connection to the server at [" + _host + ":" + _port + "] FAILED", ex);
        }
        MainLogger.logger.info("Connection to : [" + _host + ":" + _port + "], was successfully initialized.");
        return _singeltonConnection;
    }

    static void setConnectionParameters(String host, String userName, String password, String port) {
        _host = host;
        _userName = userName;
        _password = password;
        _port = port;
    }

    /**
     * silently close the connection.
     */
    static void silentlyCloseConnection() {
        _host = null;
        _userName = null;
        _password = null;
        _port = null;
        try {
            if (_singeltonConnection != null && !_singeltonConnection.isClosed()) {
                _singeltonConnection.close();
                MainLogger.logger.info("Connection was closed successfully");
            }
        } catch (SQLException ex) {/*Empty*/

        }
    }
}
